package com.atguigu.rabbitmq.routing;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @ClassNAME Consumer
 * @Description
 * @Author wuyafeng atguigu
 * @Date 2021/11/30 14:46
 * @Version 1.0
 **/
public class Consumer1 {
    public static void main(String[] args) throws IOException, TimeoutException {
        //定义队列名称
        String queueName = "test_direct_queue1";

        //一、初始化连接
        //1.创建连接对象  默认端口 5672
        ConnectionFactory connectionFactory = new ConnectionFactory();
        //2. 设置主机
        connectionFactory.setHost("localhost");
        //3. 设置需要连接的端口
        connectionFactory.setPort(5672);
        //4. 设置虚拟机，   默认 /
        connectionFactory.setVirtualHost("/");
        //5. 设置用户名和密码
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");

        //二、获取连接对象
        Connection connection = connectionFactory.newConnection();
        //三、获取频道
        Channel channel = connection.createChannel();

        //四、获取消息
        DefaultConsumer consumer = new DefaultConsumer(channel){
            /**
             * 回调函数，获取消息时，会自动执行
             * @param consumerTag
             * @param envelope
             * @param properties
             * @param body
             * @throws IOException
             */
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                //  super.handleDelivery(consumerTag, envelope, properties, body);
//                System.out.println("消费标识 "+consumerTag);
//                System.out.println("交换机："+envelope.getExchange());
//                System.out.println("路由key "+envelope.getRoutingKey());
//                System.out.println("properties=="+properties);
                System.out.println("body===" + new String(body));
            }
        };
        //从频道中获取消息
        /**
         * String queue, 队列名称， 需要与发送端 保持一致
         * boolean autoAck, 是否自动确认
         * Consumer callback  回调对象
         */
        channel.basicConsume(queueName,true,consumer);
    }
}
